"""
消息模型
"""
from sqlalchemy import Column, String, Integer, ForeignKey, Text, Boolean, Enum as SQLEnum
from sqlalchemy.orm import relationship
import enum

from app.models.base import BaseModel


class MessageRole(str, enum.Enum):
    """消息角色枚举"""
    USER = "user"           # 用户消息
    ASSISTANT = "assistant" # AI助手消息
    SYSTEM = "system"       # 系统消息
    FUNCTION = "function"   # 函数调用结果


class MessageType(str, enum.Enum):
    """消息类型枚举"""
    TEXT = "text"           # 文本消息
    IMAGE = "image"         # 图片消息
    FILE = "file"           # 文件消息
    FUNCTION_CALL = "function_call"  # 函数调用
    ERROR = "error"         # 错误消息


class Message(BaseModel):
    """消息模型"""
    
    __tablename__ = "messages"
    
    # 关联对话
    conversation_id = Column(
        Integer,
        ForeignKey("conversations.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
        comment="对话ID"
    )
    
    # 消息内容
    role = Column(
        SQLEnum(MessageRole),
        nullable=False,
        comment="消息角色"
    )
    message_type = Column(
        SQLEnum(MessageType),
        default=MessageType.TEXT,
        nullable=False,
        comment="消息类型"
    )
    content = Column(Text, nullable=False, comment="消息内容")
    
    # 附加信息
    tokens = Column(Integer, nullable=True, comment="Token数量")
    model = Column(String(50), nullable=True, comment="使用的模型")
    
    # 函数调用相关
    function_name = Column(String(100), nullable=True, comment="调用的函数名")
    function_args = Column(Text, nullable=True, comment="函数参数（JSON）")
    function_result = Column(Text, nullable=True, comment="函数结果（JSON）")
    
    # 知识库检索相关
    retrieved_docs = Column(Text, nullable=True, comment="检索到的文档（JSON）")
    relevance_score = Column(String(20), nullable=True, comment="相关性分数")
    
    # 标记
    is_error = Column(Boolean, default=False, comment="是否错误消息")
    error_message = Column(Text, nullable=True, comment="错误信息")
    
    # 用户反馈
    is_helpful = Column(Boolean, nullable=True, comment="是否有帮助")
    user_feedback = Column(Text, nullable=True, comment="用户反馈")
    
    # 关系
    conversation = relationship("Conversation", back_populates="messages")
    
    def __repr__(self):
        return f"<Message(id={self.id}, role={self.role}, type={self.message_type})>"
    
    @property
    def is_user_message(self) -> bool:
        """是否用户消息"""
        return self.role == MessageRole.USER
    
    @property
    def is_assistant_message(self) -> bool:
        """是否助手消息"""
        return self.role == MessageRole.ASSISTANT
    
    def to_llm_format(self) -> dict:
        """转换为LLM API格式"""
        return {
            "role": self.role.value,
            "content": self.content
        }

